package com.yoomiito.app.ui.anyview.invite

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Handler
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestBuilder
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.google.zxing.WriterException
import com.yoomiito.app.R
import com.yoomiito.app.adapter.my.InviteFriendAdAdapter
import com.yoomiito.app.model.my.InviteFriend
import com.yoomiito.app.share.ui.BaseShareView
import com.yoomiito.app.utils.*
import com.yoomiito.app.widget.SpacingDecoration

/**
 * 邀请好友
 */
class InviteFriendView(override var context: Activity, val frameLayout: FrameLayout):BaseShareView(context) {

    private lateinit var parentView: View
    private lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView
    private lateinit var inviteCode:String
    private lateinit var friendAdAdapter: InviteFriendAdAdapter

    private lateinit var mContainerInviteCode: LinearLayout

    init {
        initView()
        initRcy()
        initAd()
    }

    private fun initView() {
        parentView = LayoutInflater.from(context).inflate(R.layout.view_invite_friend, null, false)
        mRecyclerView = parentView.findViewById(R.id.rcy)
        mShowADView = parentView.findViewById(R.id.ad_view)
        val lp = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
        frameLayout.addView(parentView, lp)
    }

    private fun initRcy() {
        mRecyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context, androidx.recyclerview.widget.RecyclerView.HORIZONTAL, false)
        mRecyclerView.addItemDecoration(SpacingDecoration(DensityUtil.dp2px(6f), 0, false))
        friendAdAdapter = InviteFriendAdAdapter(null)
        mRecyclerView.adapter = friendAdAdapter
        friendAdAdapter.setOnItemClickListener { _, _, position ->
            makeCodeView(friendAdAdapter.data[position].color)
            val info = friendAdAdapter.data[position]
            makeThemeAd(info.img_url, info.defaultResource)
        }
    }

    private fun initAd() {
        mAdView = LayoutInflater.from(context).inflate(R.layout.item_invite_friend_1, null, false)
        mAdIv = mAdView.findViewById(R.id.ad_iv)
        val mUserPhoto = mAdView.findViewById<ImageView>(R.id.user_photo)
        val mUserName = mAdView.findViewById<TextView>(R.id.user_name)
        mContainerInviteCode = mAdView.findViewById(R.id.invite_friend_invite_code)
        mErWeiMaIv = mAdView.findViewById(R.id.invite_friend_erweima)

        val userInfo = UserInfoConfig.getUser()
        inviteCode = userInfo.invitation_code
        mUserName.text = userInfo.name
        ImageLoader.getInstance().into(context, userInfo.headimgurl, mUserPhoto)
//        val configInfo = UserInfoConfig.getConfigInfo()
//        makeErWeiMa(configInfo!!.invite_url.value)
    }

//    private fun makeErWeiMa() {
//        val configInfo = UserInfoConfig.getConfigInfo()
//        try {
//            mErWeiMaIv.setImageBitmap(ZxingUtil.cretaeZxing(configInfo!!.invite_url.value, ResUtil.getColor(R.color.color_black)))
//        } catch (e: WriterException) {
//            e.printStackTrace()
//        }
//    }

    //把邀请码添加到布局上
    private fun makeCodeView(color: String) {
        var color = color
        if (!color.startsWith("#")) {
            color = "#$color"
        }
        L.i("color: $color")
        if (mContainerInviteCode.childCount == 0) {
            initCodeView(color)
        } else {
            setBgColorForInviteCode(color)//5d51f0  2849f2  f75735 ef3a11
        }
    }

    private fun setBgColorForInviteCode(color: String) {
        val size = mContainerInviteCode.childCount
        for (i in 0 until size) {
            val view = mContainerInviteCode.getChildAt(i)
            if (view is TextView) {
                val drawable = view.background as GradientDrawable
                drawable.setColor(Color.parseColor(color))
            }
        }
    }

    private fun initCodeView(color: String) {
        val code = inviteCode.toCharArray()
        val lp = mContainerInviteCode.layoutParams as LinearLayout.LayoutParams
        val parentWidth = lp.width
        val div = DensityUtil.dp2px(2f)
        val width = (parentWidth - (code.size - 1) * div) / code.size
        for (i in code.indices) {
            val tv = TextView(context)
            val tvLp = LinearLayout.LayoutParams(width, width)
            tv.gravity = Gravity.CENTER
            tv.setTextColor(ResUtil.getColor(R.color.color_white))
            tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30f)
            tv.setBackgroundResource(R.drawable.bg_invite_code_3)
            val drawable = tv.background as GradientDrawable
            drawable.setColor(Color.parseColor(color))
            tv.typeface = AllUtils.getTypeface()
            tv.text = code[i].toString()
            tv.layoutParams = tvLp
            mContainerInviteCode.addView(tv)
            if (i != 0 || i != code.size - 1) {
                val line = View(context)
                val viewLp = LinearLayout.LayoutParams(div, 0)
                line.layoutParams = viewLp
                mContainerInviteCode.addView(line)
            }
        }
    }

    override fun setData(any: Any) {
        var inviteFriend = any as InviteFriend
        if (inviteFriend?.data == null || inviteFriend.data.size == 0) {
            inviteFriend = InviteFriend()
            val infos = arrayListOf<InviteFriend.InviteFriendInfo>()
            val info = InviteFriend.InviteFriendInfo()
            info.color = "#ef3a11"
            info.defaultResource = R.drawable.default_invite_friend
            info.title = "海量优惠券"
            infos.add(info)
            inviteFriend.data = infos
        }
        friendAdAdapter.setNewData(inviteFriend.data)
        makeCodeView(inviteFriend.data[0].color)
        ImageUtils.layoutView(mAdView)
        makeErWeiMa(inviteFriend.invite_url)
        makeThemeAd(inviteFriend.data[0].img_url, inviteFriend.data[0].defaultResource)


//        val builder: RequestBuilder<Bitmap> = if (inviteFriend.data[0].defaultResource == 0) {
//            Glide.with(context).asBitmap().load(inviteFriend.data[0].img_url)
//        } else {
//            Glide.with(context).asBitmap().load(inviteFriend.data[0].defaultResource)
//        }
//
//        builder.into(object : SimpleTarget<Bitmap>() {
//            override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
//                mAdIv.background = ImageUtils.bitmapToDrawable(resource)
//                Handler().postDelayed({
//                    ImageUtils.createBitmapByView(context,mAdView)
//                    ImageUtils.layoutView(mAdView, DensityUtil.dp2px(375f), DensityUtil.dp2px(667f))
//                    val mBitmap = ImageUtils.viewSaveToImage(mAdView)
//                    makeBitmapListener(mBitmap)
//                    mShowADView.setImageBitmap(mBitmap)
//                },1000)
//
//            }
//        })
    }
}